package com.alogic.vfs.xscript;

import com.alogic.xscript.AbstractLogiclet;
import com.alogic.xscript.ExecuteWatcher;
import com.alogic.xscript.Logiclet;
import com.alogic.xscript.LogicletContext;
import com.alogic.xscript.doc.XsObject;
import com.anysoft.util.BaseException;
import com.anysoft.util.Properties;
import com.anysoft.util.PropertiesConstants;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.lang3.StringUtils;


/**
 * 获取上传文件的图像格式
 *
 * @since  1.6.13.14 [20200907 duanyy] <br>
 */
public class UploadImageType extends AbstractLogiclet {
    protected String pid = "$upload";
    protected String id;
    public static final String TYPE_JPG = "jpg";
    public static final String TYPE_GIF = "gif";
    public static final String TYPE_PNG = "png";
    public static final String TYPE_BMP = "bmp";
    public static final String TYPE_UNKNOWN = "unknown";

    public UploadImageType(String tag, Logiclet p) {
        super(tag, p);
    }

    @Override
    public void configure(Properties p){
        super.configure(p);

        pid = PropertiesConstants.getString(p,"pid",pid,true);
        id = PropertiesConstants.getString(p,"id","$" + getXmlTag(),true);
    }

    @Override
    protected void onExecute(XsObject root, XsObject current, final LogicletContext ctx, final ExecuteWatcher watcher){
        FileItem fileItem = ctx.getObject(pid);
        if (fileItem == null){
            throw new BaseException("core.e1001","It must be in a upload-scan context,check your together script.");
        }

        if (StringUtils.isNotEmpty(id)){
            byte[] data = fileItem.get();
            ctx.SetValue(id,getImageType(data));
        }
    }

    private static String bytesToHexString(byte[] src,int start,int length){
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = start; i < length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }

    public static String getImageType(byte[] data) {
        if (data == null || data.length < 4){
            return TYPE_UNKNOWN;
        }
        String type = bytesToHexString(data,0,4).toUpperCase();
        if (type.contains("FFD8FF")) {
            return TYPE_JPG;
        } else if (type.contains("89504E47")) {
            return TYPE_PNG;
        } else if (type.contains("47494638")) {
            return TYPE_GIF;
        } else if (type.contains("424D")) {
            return TYPE_BMP;
        }else{
            return TYPE_UNKNOWN;
        }
    }
}
